from typing import List
import zlib
from utils.创建文件夹 import createFolder
from utils.JSON的输入和输出 import 写入json
from utils.prefixlen为1的name import prefix_1_names
from utils.文件夹下的所有文件 import getFilesList

# 这里可以设置只提取一个文件
# source_files = ['IDS_STRUCTURE_SELECT']
source_files = getFilesList("output/IDS导出的资源/日文")


def output(
    str_divided: List[List[str]], str_divided_en: List[List[str]], output_path: str
):
    map = dict()
    for i in range(0, len(str_divided_en), 2):
        map[str_divided_en[i]] = str_divided_en[i + 1]
    res = []
    for i in range(0, len(str_divided), 2):
        word = {
            "COMMAND": str_divided[i],
            "source": str_divided[i + 1],
            "source_en": map.get(str_divided[i]),
            "trans": "",
        }
        res.append(word)
    # 输出到文件
    写入json(res, output_path)


def progressiveDivide(b: bytes) -> List[List[str]]:
    def helper(b: bytes):  # 返回读取到的第一个句子 以及后面剩余的字节
        # 读取第一个字节
        b_first = b[0]
        # 计算它代表的长度
        length = b_first - 0xA0
        # 长度是57的话 就是一个特殊字符
        # 58 后面一个字节×256加上后面第二个字节
        if length == 57:
            # 第二个字节对应的字符代表了长度
            length = b[1]
            return [b[2 : 2 + length].decode("utf-8"), b[2 + length :]]
        if length == 58:
            length = b[1] * 256 + b[2]
            return [b[3 : 3 + length].decode("utf-8"), b[3 + length :]]
        else:
            return [
                b[1 : 1 + length].decode("utf-8", "backslashreplace"),
                b[1 + length :],
            ]

    res = []
    while len(b):
        item, b = helper(b)[0], helper(b)[1]
        # print(item)
        res.append(item)
    return res


def 解压(
    file_name: str,
    file_name_en: str,
    output_dir: str,
    output_name: str,
    prefix_len: int = 3,
):
    def getStrDivided(file_name: str, prefix_len: int) -> List[List[str]]:
        with open(file_name, "rb") as f:
            b = f.read()  # 读取文件内容 二进制
        out = zlib.decompress(b[8:])  # 解压
        str_divided = progressiveDivide(out[prefix_len:])  # 将前三个\xde\x00\xa9之外的送去分割
        return str_divided

    str_divided = getStrDivided(file_name, prefix_len)
    str_divided_en = getStrDivided(file_name_en, prefix_len)
    print(len(str_divided), len(str_divided_en))

    output(str_divided, str_divided_en, output_dir + "/" + output_name)


if __name__ == "__main__":
    for name in source_files:
        prefix_len = 3
        if name in prefix_1_names:
            prefix_len = 1
        print(name)
        print(prefix_len)
        createFolder("output/IDS_To_JSON")
        解压(
            f"output/IDS导出的资源/日文/{name}",
            f"output/IDS导出的资源/英文/{name}",
            "output/IDS_To_JSON",
            f"{name}.json",
            prefix_len,
        )
